/**
 * Created by zzy on 2016/12/8.
 */
var $ = require('jquery');
require('easyui');
require('layout/uiJs');
require('js-path/jquery-validation-wrapper');
var $alert = require("libs/alert");
var $confirm = require("libs/confirm");
var modifyOutroomOrderValidator = null;
var modifyDeliveryCodeValidator = null;
var isSale = require('libs/user-type').isSale;
var statusArr = [{
    label: '已提交',
    value: 'commit'
},{
    label: '未提交',
    value: 'uncommit'
},{
    label: '拣货中',
    value: 'picking'
},{
    label: '已拣货',
    value: 'pick'
},{
    label: '已打包',
    value: 'pack'
},{
    label: '已称重',
    value: 'weight'
},{
    label: '已出库',
    value: 'outroom'
},{
    label: '缺货',
    value: 'outstock'
},{
    label: '取消中',
    value: 'canceling'
},{
    label: '已取消',
    value: 'canceled'
}];
$(function () {
    $('#ft').show();
    var status = {
        uncommit: '未提交',
        commit: '已提交',
        picking: '拣货中',
        pick: '已拣货',
        pack: '已打包',
        weight: '已称重',
        outroom: '已出库',
        outstock: '缺货',
        canceling: '取消中',
        canceled: '已取消'
    };
    var $statusSelect = $('#status');
    $statusSelect.combobox({
        data: statusArr,
        valueField:'value',
        textField:'label',
        multiple:true,
        panelHeight:'auto'
    });
    $('#search').on('click',function () {
        var formData = $('#searchForm').serializeObject();
        var statusList = formData.statusList;
        if(statusList && statusList.length > 0){
            if($.inArray('all',statusList) === -1){
                formData.statusList = statusList.toString();
            }else{
                delete formData.statusList;
            }
        }
        formData.orderCreateFromDt = $('#startDt').data('utc0');
        formData.orderCreateToDt = $('#endDt').data('utc0');
        $('#outOrderTable').datagrid('load',formData);
    });
    $(document).on('click','a[name=orderDetail]',function () {
        window.parent.tabOpen($(this).attr('ref'),'出库单详情',true,true);
    });
    $(document).on('click','a[name=entDetail]',function () {
        window.parent.tabOpen($(this).attr('ref'),'客户公司',true,true);
    });
    $(document).on("click",'a[name=getDeliveryCode]',function () {
        var id = $(this).data('id');
        $confirm("是否获取运单号？",function () {
            ajaxRequestMethod({id: id},"api/v1/p/mms/outRoomOrder/getDeliveryCode");
        });
    });

    
    $(document).on('click','.handler',function (e) {
        var $this = $(this);
        var scene = $this.attr('name');
        if(scene == 'modifyOutroomOrder'){
            var full = $this.data('full');

            $('#modifyOutroomOrderModal').modal('show',{
                id: full.id,
                recipientName: full.recipientName,
                recipientCountryId: full.recipientCountryId,
                recipientRegionName: full.recipientRegionName,
                recipientCityName: full.recipientCityName,
                recipientZipcode: full.recipientZipcode,
                recipientAddress1: full.recipientAddress1,
                recipientAddress2: full.recipientAddress2,
                recipientPhone: full.recipientPhone,
                recipientEmail: full.recipientEmail,
                orderNo:full.orderNo
            });
        }else if(scene == 'modifyDeliveryCode'){
            var full = $this.data('full');
            $('#modifyDeliveryCodeModal').modal('show',{
                orderId: full.id,
                orderNo:full.orderNo,
                deliveryCode: full.deliveryCode
            });
        }else{
            return false;
        }
    });
    $('#modifyOutroomOrderModal').on('show.bs.modal',function (e) {
        var rel = e.relatedTarget;
        $("#recipientCountryId").combobox("setValue",rel.recipientCountryId);
        $('#modifyOutroomOrderForm').setForm(rel);
    });
    $('#modifyOutroomOrderModal').on('hidden.bs.modal',function (e) {
        modifyOutroomOrderValidator.resetForm();
    });
    $('#modifyOutroomOrderCommit').on('click',function (e) {
        $('#modifyOutroomOrderForm').submit();
    });
    modifyOutroomOrderValidator = $('#modifyOutroomOrderForm').validateWapper({
        rules: {
            recipientName: {
                required: true
            },
            recipientCityName: {
                required: true
            },
            recipientZipcode: {
                required: true
            },
            recipientAddress1: {
                required: true
            },
            recipientPhone: {
                required: true
            }
        },
        messages: {
            recipientName: {
                required: '必填'
            },
            recipientCityName: {
                required: '必填'
            },
            recipientZipcode: {
                required: '必填'
            },
            recipientAddress1: {
                required: '必填'
            },
            recipientPhone: {
                required: '必填'
            }
        },
        submitHandler: function() {
            var formData = $('#modifyOutroomOrderForm').serializeObject();
            $.ajax({
                url: 'api/v1/p/mms/outRoomOrder/update',
                type: 'post',
                data: JSON.stringify(formData),
                contentType: 'application/json;charset=utf-8'
            })
                .done(function (res) {
                    if(res.code==200){
                        $('#modifyOutroomOrderModal').modal('hide');
                        $('#outOrderTable').datagrid('reload');
                    }else{
                        $alert(res.message);
                    }
                });
        }
    });

    $('#modifyDeliveryCodeModal').on('show.bs.modal',function (e) {
        var rel = e.relatedTarget;
        $('#modifyDeliveryCodeForm').setForm(rel);
    });
    $('#modifyDeliveryCodeModal').on('hidden.bs.modal',function (e) {
        $('#modifyDeliveryCodeForm').find('input').val('').end().find('p').text('');
        modifyDeliveryCodeValidator.resetForm();
    });
    $('#modifyDeliveryCodeCommit').on('click',function (e) {
        $('#modifyDeliveryCodeForm').submit();
    });
    modifyDeliveryCodeValidator = $('#modifyDeliveryCodeForm').validateWapper({
        rules: {
            deliveryCode: {
                required: true
            }
        },
        messages: {
            deliveryCode: {
                required: '必填'
            }
        },
        submitHandler: function() {
            var formData = $('#modifyDeliveryCodeForm').serializeObject();
            $.ajax({
                url: 'api/v1/p/mms/outRoomOrder/updateDeliveryCode',
                type: 'post',
                data: JSON.stringify(formData),
                contentType: 'application/json;charset=utf-8'
            })
                .done(function (res) {
                    if(res.code==200){
                        $('#modifyDeliveryCodeModal').modal('hide');
                        $('#outOrderTable').datagrid('reload');
                    }else{
                        $alert(res.message);
                    }
                });
        }
    });
    comboxInit('api/v1/p/mms/area/query',{'level':'1'}
        ,$("#recipientCountryId"));

    warehouseInit();
    tableInit();
    function warehouseInit() {
        $('select[name=warehouseId]').combobox({
            url:'api/v1/p/crm/warehouse/query',
            valueField:'warehouseId',
            textField:'warehouseName',
            queryParams:{
                warehouseType:'DEST'
            },
            loadFilter:function(result){
                if(result.code=='200'){
                    result.data.unshift({warehouseId:'',warehouseName:'全部'});
                    return result.data;
                }
            }
        })
    }
    function tableInit() {
        $('#outOrderTable').datagrid({
            url:'api/v1/p/mms/outRoomOrder/list',
            border : false,
            height:$(window).height(),
            pagination : true,
            pageSize : 20,
            pageList : [ 20, 50,  100 ],
            emptyMsg : "暂无数据",
            singleSelect: true,
            rownumbers:true,
            columns:[[
                {
                    field:'orderNo',
                    title:'订单号',
                    width:'11%',
                    formatter:function (value,row,index) {
                        return "<a class='ellipsis' href='javascript:;' ref='out-order-detail?id="+row.id+"' name='orderDetail' data-id='"+row.id+"' title='"+value+"'>"+value+"</a>";
                    }
                },{
                    field:'entName',
                    title:'客户名称',
                    width:'9%',
                    formatter:function (value,row,index) {
                        return "<a class='ellipsis' href='javascript:;' ref='company-detail?id="+row.entId+"' name='entDetail' title='"+value+"'>"+value+"</a>";
                    }
                },
                {
                    field:'warehouseName',
                    title:'海外仓',
                    width:'8%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'platType',
                    title:'电商平台',
                    width:'5%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'deliveryWayName',
                    title:'发货方式',
                    width:'9%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'deliveryCode',
                    title:'物流单号',
                    width:'10%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'deliveryWeight',
                    title:'发货重量Kg',
                    width:'6%'
                },{
                    field:'createDt',
                    title:'下单时间',
                    width:'9%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'commitDate',
                    title:'提交时间',
                    width:'9%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'outroomDate',
                    title:'出库时间',
                    width:'9%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'status',
                    title:'状态',
                    width:'5%',
                    formatter:function (value,row,index) {
                        return status[value];
                    }
                },{
                    field:'opertation',
                    title:'操作',
                    hidden:isSale,
                    width:'10%',
                    formatter:function (value,row,index) {
                        var htmlArr = [];
                        var noOut = $.inArray(row.status,['commit','pick','pack','weight','uncommit']) != -1;
                        if(!row.deliveryCode && noOut){
                            htmlArr.push("<a href='javascript:;' name='getDeliveryCode' data-id='"+row.id+"'>获取运单号</a>");
                        }
                        if(noOut){
                            htmlArr.push("<a class='handler' href='javascript:;' name='modifyOutroomOrder' data-full='"+JSON.stringify(row)+"'>修改</a>");
                        }
                        if(row.deliveryCode && noOut){
                            htmlArr.push("<a class='handler' href='javascript:;' name='modifyDeliveryCode' data-full='"+JSON.stringify(row)+"'>修改运单</a>");
                        }
                        var html = '';
                        $.each(htmlArr,function (i,o) {
                            if(i === 0){
                                html += o;
                            }else{
                                if(i % 2===0){
                                    html += '<br>'+o;
                                }else{
                                    html += '|'+o;
                                }
                            }
                        });
                        return html;
                    }

                }
            ]],
            loadFilter:function(data){
                if(data.code == '200'){
                    return data.data;
                }else{
                    return [];
                }
            },
            toolbar:"#tb"
        });
    }
});
function ajaxRequestMethod(data,url) {
    $.ajax({
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(data),
        type:"post",
        url:url,
        success:function (result) {
            if(result.code==200){
                $('#outOrderTable').datagrid('load');
            }else {
                $alert(result.message);
            }
        },
        error:function () {
            console.log(url+" error")
        }
    });
}
//添加参数
function comboxInit(url,data,$select) {
    $select.combobox({
        url:url,
        valueField:'id',
        textField:'name',
        queryParams:data,
        loadFilter:function(result){
            if(result.code=='200'){
                return result.data;
            }
        }
    })
}